<?php
class MAIN_Controller_Action extends System_Controller_Action {
	function init() {
		parent::init();
		$params = $this->_request->getParams();
		$this->_setLoginIdentity($params);
		if(!class_exists('Zend_Auth'))Zend_loader :: loadClass('Zend_Auth');
		$auth = Zend_Auth :: getInstance();
		$identity = $auth->getIdentity();
        if ($this->_output == "html") {
	            if(Zend_Registry::isRegistered("view")) {
	                $view = Zend_Registry::get("view");
	            } else {
	                $view = new Smarty_View();
	            }
		        $config = Zend_Registry :: get("app-config");
		        $data["_title"] = $config->title;
			    $view->assign("",$data);
			    $view->assign("params",$params);
	            Zend_Registry :: set("view", $view);
        }
	}
	public function preDispatch() {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->viewRenderer = null;
	}
	public function _setLoginIdentity($params){
		if($params['fields'] && $params['login_cmd'] && $params['login_cmd']=="add"){
			$username = $params['fields']['txt_userid'];
			//$password = md5($params['fields']['txt_pwd']);
			$password = $params['fields']['txt_pwd'];
			$this->loginUser($username,$password,1);
		}
	}
	protected function loginUser($username,$password,$redirect=null){
		Zend_Loader :: loadClass("Zend_Auth_Adapter_DbTable");
		$dbAdapter= Zend_Registry :: get("db");
		$authAdapter= new Zend_Auth_Adapter_DbTable($dbAdapter);
		$auth = Zend_Auth :: getInstance();
		$generic = System_Controller::getGeneric("index","front");
		$logindata = $generic->getLoginUser($username,$password);
		if ($logindata['userid']) {
			$data = $authAdapter->getResultRowObject(null, "user_name");
			$data->userid = $logindata['userid'];
			$data->user_prename = $logindata['user_prename '];
			$data->user_name = $logindata['user_name'];
			$data->user_surname = $logindata['user_surname'];
			$data->group_name = $logindata['group_name'];
			$data->usertype_description = $logindata['usertype_description'];
			$auth->getStorage()->write($data);
			setcookie("username_log", $username, time()+3600*24*356);
			setcookie("password_log", $password, time()+3600*24*356);
			if($redirect)
				$this->_redirect(APP_URL."/preauthorize");
		}else{
			if($redirect){
				$link = APP_URL."/";
				echo "<script>" .
						"alert('Username or Password is incorrect!'); " .
						"window.location.href='".$link."'; " .
						"</script>";
			}
		}
	}
}